import time

import cv2
from flask import session, render_template, redirect, url_for, Response
from controller.modules.home import home_blu
from controller.utils.camera import VideoCamera

video_camera = None
global_frame = None


# 主页
@home_blu.route('/')
def index():
    # 模板渲染
    username = session.get("username")
    if not username:
        return redirect(url_for("user.login"))
    return render_template("camera/photo.html")


# 获取视频流
def video_stream():
    global video_camera
    global global_frame

    face_model = cv2.CascadeClassifier('controller/static/haarcascade_frontalface_default.xml')
    # opencv中视频录制需要借助VideoWriter对象， 将从VideoCapture 中读入图片，不断地写入到VideoWrite的数据流中。
    # 指定视频编解码方式为DIV3
    isRecording = False
    codec = cv2.VideoWriter_fourcc('D', 'I', 'V', '3')
    fps = 10  # 指定写入帧率为25
    frameSize = (640, 480)  # 指定窗口大小
    output = None

    if video_camera is None:
        cap = cv2.VideoCapture(0)  # 定义视频捕获类cap

    while True:
        ret, frame = cap.read()  # 定义read对象ret和frame帧
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_model.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=4)  # 检测人脸

        for (x, y, w, h) in faces:
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
            # 发短信
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + cv2.imencode(".jpg", frame)[1].tobytes() + b'\r\n\r\n')
            # 如果没有在录制就开始录制
            if not isRecording:
                isRecording = True
                # # 创建 VideoWriter对象
                timeString = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
                timeString = 'controller/static/406--' + timeString + '.MP4'
                output = cv2.VideoWriter(timeString, codec, fps, frameSize)
                time_start = time.time()

        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + cv2.imencode(".jpg", frame)[1].tobytes() + b'\r\n\r\n')
        # 不断的从VideoCapture 中读入图片，然后写入到VideoWrite的数据流中。
        if isRecording:
            if time.time() - time_start < 300:
                output.write(frame)
            else:
                output.release()
                isRecording = False


# 视频流
@home_blu.route('/video_viewer')
def video_viewer():
    # 模板渲染
    username = session.get("username")
    if not username:
        return redirect(url_for("user.login"))
    return Response(video_stream(),
                    mimetype='multipart/x-mixed-replace; boundary=frame')
